﻿using System;
using System.Diagnostics;
using System.Linq;

namespace AdbRegisterUtils
{
    /// <summary>
    /// ADB进程管理器
    /// </summary>
    public static class AdbProcessManager
    {
        /// <summary>
        /// 强制终止所有ADB相关进程
        /// </summary>
        public static void KillAllAdbProcesses()
        {
            try
            {
                Console.WriteLine("[AdbProcessManager] 正在终止所有ADB进程...");

                // 要终止的进程名称列表
                string[] processNames = { "adb", "fastboot" };
                int killedCount = 0;

                foreach (string processName in processNames)
                {
                    killedCount += KillProcessesByName(processName);
                }

                // 验证是否还有ADB进程运行
                if (VerifyNoAdbProcessesRunning())
                {
                    Console.WriteLine($"[AdbProcessManager] 成功终止 {killedCount} 个ADB进程");
                }
                else
                {
                    Console.WriteLine($"[AdbProcessManager] 警告：可能仍有ADB进程在运行");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbProcessManager ERROR] 终止ADB进程失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 根据进程名终止进程
        /// </summary>
        private static int KillProcessesByName(string processName)
        {
            int killedCount = 0;

            try
            {
                // 获取所有指定名称的进程（不区分.exe扩展名）
                var processes = Process.GetProcesses()
                    .Where(p => p.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase) ||
                               p.ProcessName.Equals(processName + ".exe", StringComparison.OrdinalIgnoreCase))
                    .ToList();

                foreach (var process in processes)
                {
                    try
                    {
                        if (!process.HasExited)
                        {
                            process.Kill();
                            // 等待进程结束，最多等待1秒
                            if (process.WaitForExit(1000))
                            {
                                killedCount++;
                                Console.WriteLine($"[AdbProcessManager] 已终止: {process.ProcessName} (PID: {process.Id})");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"[AdbProcessManager ERROR] 终止进程失败 {process.ProcessName} (PID: {process.Id}): {ex.Message}");
                    }
                    finally
                    {
                        process.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[AdbProcessManager ERROR] 获取进程失败: {ex.Message}");
            }

            return killedCount;
        }

        /// <summary>
        /// 验证是否没有ADB进程在运行
        /// </summary>
        public static bool VerifyNoAdbProcessesRunning()
        {
            try
            {
                var adbProcesses = Process.GetProcesses()
                    .Where(p => p.ProcessName.IndexOf("adb", StringComparison.OrdinalIgnoreCase) >= 0)
                    .ToList();

                bool noProcessesRunning = !adbProcesses.Any();

                // 清理进程对象
                foreach (var process in adbProcesses)
                {
                    process.Dispose();
                }

                return noProcessesRunning;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取当前运行的ADB进程数量
        /// </summary>
        public static int GetAdbProcessCount()
        {
            try
            {
                var adbProcesses = Process.GetProcesses()
                    .Where(p => p.ProcessName.IndexOf("adb", StringComparison.OrdinalIgnoreCase) >= 0)
                    .ToList();

                int count = adbProcesses.Count;

                // 清理进程对象
                foreach (var process in adbProcesses)
                {
                    process.Dispose();
                }

                return count;
            }
            catch
            {
                return -1; // 表示无法获取
            }
        }
    }
}